//
//  Request.m
//  HollyCrmSdk
//
//  Created by hollycrm on 2021/4/16.
//  网络请求

#import "Request.h"

@implementation Request
-(void)post:(NSMutableDictionary *)params withUrl:(NSString *)url succ:(void (^)(NSDictionary * _Nonnull))succed fail:(void (^)(NSString * _Nonnull))failed{
    
        NSURLSession * mySession = [NSURLSession sharedSession ];
        NSURL * fullURL = [ NSURL URLWithString :url];
        NSMutableURLRequest * request = [ NSMutableURLRequest requestWithURL :fullURL cachePolicy : NSURLRequestUseProtocolCachePolicy timeoutInterval : 30.0 ];
        request. HTTPMethod = @"POST" ;
        [request addValue : @"application/json" forHTTPHeaderField : @"Content-Type" ];
        [request addValue : @"application/json" forHTTPHeaderField : @"Content-Type" ];
    
    
    NSData *data=[NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
    request. HTTPBody = data;
    
        NSURLSessionDataTask * task = [mySession dataTaskWithRequest :request completionHandler :^( NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            // 判断接口是否成功返回
            if (error) {
                // 接口访问失败
                NSLog ( @"error:%@" ,error. localizedDescription );
                NSLog ( @"%s" ,__func__);
              
                if (failed) {
                    failed(@"请求失败，请稍后再试");
                }
            } else
            {
                // 接口访问成功
                //JSON 解析
                NSError * parseError1 = nil ;
                NSDictionary * dic = [ NSJSONSerialization JSONObjectWithData :data options : NSJSONReadingMutableContainers error :&parseError1];
                if (parseError1) {
                    NSLog ( @"JSON 解析错误 " );
                    return ;
                }
                NSLog ( @"data:%@" , dic);
               
                
                
                BOOL succ = [[dic objectForKey:@"Succeed"] boolValue];
                if (succ) {
                    if (succed) {
                        dispatch_async ( dispatch_get_main_queue (), ^{
                            succed(dic);
                        });
                    }
                } else {
     
                    if (failed) {
                        dispatch_async ( dispatch_get_main_queue (), ^{
                            NSString *msg = [dic valueForKey:@"Message"];
                            if (msg != nil) {
                            failed(msg);
                            }
                            else{
                                failed(@"请求服务异常");
                            }
                        });
                    }
                }
            }
           
        }];
        [task resume];
    
}


@end
